<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>地址选择器</title>
    <link rel="stylesheet" href="__CDN__/assets/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="__CDN__/assets/css/fastadmin.min.css"/>
    <link rel="stylesheet" href="__CDN__/assets/libs/font-awesome/css/font-awesome.min.css"/>
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
        }

        #container {
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
        }

        .confirm {
            position: absolute;
            bottom: 30px;
            right: 4%;
            z-index: 99;
            height: 50px;
            width: 50px;
            line-height: 50px;
            font-size: 15px;
            text-align: center;
            background-color: white;
            background: #1ABC9C;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 50%;
        }

        .search {
            position: absolute;
            width: 400px;
            top: 0;
            left: 50%;
            padding: 5px;
            margin-left: -200px;
        }

        .amap-marker-label {
            border: 0;
            background-color: transparent;
        }

        .info {
            padding: .75rem 1.25rem;
            margin-bottom: 1rem;
            border-radius: .25rem;
            position: fixed;
            top: 2rem;
            background-color: white;
            width: auto;
            min-width: 22rem;
            border-width: 0;
            left: 1.8rem;
            box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
        }
    </style>
</head>
<body>
<script src="__CDN__/assets/libs/jquery/dist/jquery.min.js"></script>
<div class="search">
    <div class="input-group">
        <input type="text" id="searchInput" name="q" class="form-control" placeholder="输入地点"/>
        <span class="input-group-btn">
            <button type="submit" name="search" id="search-btn" class="btn btn-success">
                <i class="fa fa-search"></i>
            </button>
        </span>
    </div>
</div>
<div class="confirm">确定</div>
<div id="map" style="height: 600px;"></div>

<script type="text/javascript">
    /**
     * 一个简单调用谷歌地图API的操作类，用于查询地址或地区名称的定位
     * 当前版本: 0.0.1
     * 当前功能: 国家切换、自动完成搜索、坐标拖动（不支持直接点击）
     */

    /**
     * options {object}
     * |- mapNode {element}   地图节点
     * |- searchInpNode {element}   搜索输入框
     * |- countryNode {element}   国家选择
     * |- apiKey {string}    地图API的Key钥
     * |- callbackName {string}   加载完JS后的回调函数名
     * |- getMarkerLatLng {function}  处理marker的坐标函数
     * |- error {function}   错误信息回调函数
     */

    var GGMap = function(options) {
        this.options = options;
        this.dom = {};
        this.status = {};
        // this.countries = {
        //     'all': {
        //         center: {lat: 15, lng: 0},
        //         zoom: 2,
        //         name: "全球"
        //     },
        //     'au': {
        //         center: {lat: -25.3, lng: 133.8},
        //         zoom: 4,
        //         name: "澳洲(AU)"
        //     },
        //     'uk': {
        //         center: {lat: 54.8, lng: -4.6},
        //         zoom: 5,
        //         name: "英国(UK)"
        //     }
        // }
    };

    // 激活初始化 由外部触发
    GGMap.prototype.init = function() {
        if (this.status.script) return this;
        this.dom.script = document.createElement('script');
        this.dom.script.src = 'https://maps.googleapis.com/maps/api/js?key=' + this.options.apiKey + '&language=us&signed_in=true&libraries=places&callback=' + this.options.callbackName;
        document.querySelector('head').appendChild(this.dom.script);
        var that = this;
        // if (this.options.countryNode) {
        //     for (var i in this.countries) {
        //         if (i == '__proto__') continue;
        //         var item = document.createElement('option');
        //         item.value = i;
        //         item.innerHTML = this.countries[i].name;
        //         this.options.countryNode.appendChild(item);
        //     }
        //     this.options.countryNode.addEventListener('change',function(e) {
        //         that.toggleCountry();
        //     },false);
        // }
        this.dom.script.onload = function() {
            that.status.script = true;
        }
        return this;
    }

    // 初始化地图
    GGMap.prototype.initMap = function() {
        this.map = new google.maps.Map(this.options.mapNode,{
            zoom: 5,
            center: {
                lat:  37.090,
                lng:-95.712
            }
        });

        // 初始化自动提示搜索功能
        this.autocomplete = new google.maps.places.Autocomplete(this.options.searchInpNode);

        // 创建地点搜索对象
        this.places = new google.maps.places.PlacesService(this.map);

        // place选择的返回事件绑定
        var that = this;
        this.autocomplete.addListener('place_changed', function() {
            that.placeSelectChanged();
        });

        return this;
    }

    // place的结果返回接收处理
    GGMap.prototype.placeSelectChanged = function() {
        var place = this.autocomplete.getPlace();
        if (place.geometry) {
            // 移动到选择点去
            this.map.panTo(place.geometry.location);
            console.log(place)
            this.map.setZoom(14);
            this.markerRender(place.geometry.location.lat(),place.geometry.location.lng(),place);
            if (typeof this.options.getMarkerLatLng === 'function') {
                this.options.getMarkerLatLng(place.geometry.location.lat(),place.geometry.location.lng(),place);
            }
        } else {
            if (typeof this.options.error === 'function') {
                this.options.error('请不要回车直接搜索，目前只能选择谷歌为您匹配的列表')
            }
        }

        return this;
    };

    // 地图上的marker渲染方法
    GGMap.prototype.markerRender = function(lat,lng,place) {
        if (!this.marker) {
            this.marker = new google.maps.Marker({
                map: this.map,
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: {
                    lat: lat,
                    lng: lng
                }
            })
            var that = this;
            this.marker.addListener('dragend',function(e) {
                if (typeof that.options.getMarkerLatLng === 'function') {
                  console.log(e)
                    that.options.getMarkerLatLng(e.latLng.lat(),e.latLng.lng(),place);
                }
            })
        } else {
            this.marker.setPosition({
                lat: lat,
                lng: lng
            })
        }
        return this;
    }

    // 切换国家地区选择
    GGMap.prototype.toggleCountry = function() {
        if (!this.status.script) return this;
        var _country = this.options.countryNode.value;
        if (_country == 'all') {
            this.autocomplete.setComponentRestrictions([])
        } else {
            this.autocomplete.setComponentRestrictions({
                "country": _country
            })
        }
        this.map.setCenter(this.countries[_country].center)
        this.map.setZoom(this.countries[_country].zoom)
        return this;
    }


</script>
<script>
    var x=0;
    var y=0;
    var address=''
    var ggmap = new GGMap({
        mapNode: document.querySelector('#map'),
        searchInpNode: document.querySelector('#searchInput'),
        zoom: 4,
        center: {lat: 37.090, lng: -95.712},
        mapTypeId: 'terrain',
        apiKey: 'AIzaSyAkm0ATF7FbBbVrM47HGF5sndKDs22_-7s',
        callbackName: 'activeMap',
        getMarkerLatLng: function(lat,lng,place) {
            x=lat;
            y=lng;
            var attitude=lat+','+lng;
            $.get("https://maps.usbuydo.com/maps/api/geocode/json?latlng="+attitude+"&key=AIzaSyAkm0ATF7FbBbVrM47HGF5sndKDs22_-7s", function(result){

                if (result){
                  var  results=result['results'][0]['address_components'];
                    address=result['results'][0]['formatted_address'];
                  // console.log(results);return false;
                    for (i = 0; i <results.length; i++) {
                            if (results[i]['types'][0]=="administrative_area_level_1"){
                               // address=results[i]['short_name'];
                            }
                    }

                  //  address+=','+results[0]['long_name'];
                } 
            });
        },
        error: function(tips) {
            console.log(tips);
        }
    })
    ggmap.init();
    function activeMap() {
        ggmap.initMap();
    }
    $(document).on('click', '.confirm', function () {


        var data = {lat: x, lng: y, zoom: 4, address: address};

        close(data);
    });
    var close = function (data) {
        var index = parent.Layer.getFrameIndex(window.name);
        var callback = parent.$("#layui-layer" + index).data("callback");
        //再执行关闭
        parent.Layer.close(index);
        //再调用回传函数
        if (typeof callback === 'function') {
            callback.call(undefined, data);
        }
    };
</script>

</body>
</html>